# UdpTestServer
#==============
# P. Poliakoff 2015
#
# The UdpTestServer (to be used with the UdpTestClient is intended to test the quality of an IP link
#
# Command line arguments
# UdpTestServer [port Number]
#
# The log file: 
# date time packetcounter packet size missing packet_counter
#
#

import SocketServer
import sys
 
class TestServer(SocketServer.BaseRequestHandler):
    def handle(self):
        print("Received packet #" + str(int(self.request[0]) ))
        socket=self.request[1]
        socket.sendto(self.request[0],self.client_address)
        
#==========================================================
def startServer(address, port):
    try:
        server = SocketServer.UDPServer((address, port), TestServer)
        
        print ("Server started on address "+str(server.socket.getsockname()[0])+ " / "+str(server.socket.getsockname()[1]))
        print("")
        print ("Press ctrl-c to exit")
        print("")
        server.serve_forever()
    except:
        sys.exit ("unable to start server: error: "+str(sys.exc_info()[0]))
#==========================================================
# main program

if (len(sys.argv)==2) | (len(sys.argv)==3):
    try:
        port=int(sys.argv[1])
        if(port<0) | (port>0xFFFF):
            raise ValueError
    except:
        sys.exit("Invalid Port value: \""+sys.argv[1]+ "\" Port must be between 0 and 65535")
                
    
    if (len(sys.argv)==3):
        address=sys.argv[2]
    else:
        address="localhost"
    startServer(address,port)
else:
    print ("")
    print ("usage: UdpTestServer portNumber [localHostAddress]")
    print ("example: UdpTestServer 9999")
    sys.exit("")

